package config

import (
	"log"

	"github.com/spf13/viper"
)

type config struct {
	APIURL            string   `yaml:"api_url" mapstructure:"api_url"`
	DisplayURL        string   `yaml:"display_url" mapstructure:"display_url"`
	ExternUID         string   `yaml:"extern_uid" mapstructure:"extern_uid"`
	APPKey            string   `yaml:"app_key" mapstructure:"app_key"`
	APPSecret         string   `yaml:"app_secret" mapstructure:"app_secret"`
	ProcReceiveRefs   []string `yaml:"proc_receive_refs" mapstructure:"proc_receive_refs"`
	TagRefs           []string `yaml:"tags_refs" mapstructure:"tags_refs"`
	HeadsRefs         []string `yaml:"heads_refs" mapstructure:"heads_refs"`
	MergeRequestsRefs []string `yaml:"merge_requests_refs" mapstructure:"merge_requests_refs"`
	// LegacyPath is the old implementation of proc-receive executable used to keep backward
	// compatibility with agit-txn mode
	LegacyPath string `yaml:"legacy_path" mapstructure:"legacy_path"`
	Platform   string `yaml:"platform" mapstructure:"platform"`
	Alog       struct {
		FilePath    string `yaml:"log_file" mapstructure:"log_file"`
		Level       string `yaml:"log_level" mapstructure:"log_level"`
		MaxSize     int    `yaml:"log_max_size" mapstructure:"log_max_size"`
		MaxBackup   int    `yaml:"log_max_backup" mapstructure:"log_max_backup"`
		MaxAge      int    `yaml:"log_max_age" mapstructure:"log_max_age"`
		Compress    bool   `yaml:"log_compress" mapstructure:"log_compress"`
		ServiceName string `yaml:"log_service_name" mapstructure:"log_service_name"`
	}
}

var Cfg config

// LoadConfig parses config file
func LoadConfig() {
	viper.SetConfigName("proc-receive")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("$HOME")
	viper.AddConfigPath("/home/git/config")

	viper.SetDefault("legacy_path", "/home/git/hooks/proc-receive-legacy")

	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			log.Fatalf("config file not found: %v", err)
		} else {
			log.Fatalf("failed to load config: %v", err)
		}
	}

	if err := viper.Unmarshal(&Cfg); err != nil {
		log.Fatalf("failed to unmarshal config: %v", err)
	}
}
